package sortingRMI_server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import sortingRMI_client.ISorter;
import sortingRMI_client.PreSortChecker;

@SuppressWarnings("rawtypes")
public class Bubblesort extends UnicastRemoteObject implements ISorter {
	private static final long serialVersionUID = -5301789120955200306L;

	protected Bubblesort() throws RemoteException {
		super();
	}
	
	private Comparable[] sortList;

	@SuppressWarnings({ "unchecked", "static-access" })
	public Comparable[] sort( Comparable[ ] arrayToBeSorted )
	{
		int j;
		boolean flag = true;
		Comparable holdingValue;
		PreSortChecker PreSort = new PreSortChecker();

		// Check for empty or null array
		if (arrayToBeSorted == null || arrayToBeSorted.length == 0){
			throw new IllegalArgumentException("Array to be sorted must not be empty!\n");
		}

		// Check for pre-sorted array
		if (PreSort.checkSort(arrayToBeSorted)) {
			//System.out.println("Array is pre-sorted!\n");
			return arrayToBeSorted;
		}
		
		// Check for 1 element array
		if (arrayToBeSorted.length == 1) {
			return arrayToBeSorted;
		}

		sortList = arrayToBeSorted;

		while ( flag )
		{
			flag= false;    //set flag to false awaiting a possible swap
			for( j=0;  j < sortList.length -1;  j++ )
			{
				if ( sortList[ j ].compareTo(sortList[j+1]) > 0 )
				{
					holdingValue = sortList[ j ];                //swap elements
					sortList[ j ] = sortList[ j+1 ];
					sortList[ j+1 ] = holdingValue;
					flag = true;              //shows a swap occurred 
				}
			}
		}
		return sortList;
	}
}